package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioPropertis;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioPropertis minioPropertis;
    @Override
    public String upload(MultipartFile file) throws Exception{

        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(minioPropertis.getBucketName()).build();
        if (!minioClient.bucketExists(bucketExistsArgs)){
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(minioPropertis.getBucketName()).build();
            minioClient.makeBucket(makeBucketArgs);

            SetBucketPolicyArgs config = SetBucketPolicyArgs.builder().bucket(minioPropertis.getBucketName()).config(
                    """
                            { "Statement" : [ {
                                             "Action" : "s3:GetObject",
                                             "Effect" : "Allow",
                                             "Principal" : "*",
                                             "Resource" : "arn:aws:s3:::%s/*"
                                           } ],
                                           "Version" : "2012-10-17"
                                         }
                             """.formatted(minioPropertis.getBucketName())

            ).build();
            minioClient.setBucketPolicy(config);
        }


        String fileName = fileName(file.getOriginalFilename());

        minioClient.putObject(PutObjectArgs.builder()
                        .bucket(minioPropertis.getBucketName())
                        .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());

        return minioPropertis.getEndpoint() + "/" + minioPropertis.getBucketName() + "/" + fileName;
    }

    public String fileName(String fileName){

        String date = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

        String uuid = UUID.randomUUID().toString();
        return date + uuid + fileName;

    }
}
